package handlers

import (
	"ecomm-manage/cache"
	"ecomm-manage/model"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	name := c.PostForm("name")
	content := c.PostForm("content")
	if name == "" || content == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能为空",
		})
		return
	}
	good := model.Good{
		Name:    name,
		Content: content,
	}
	model.DB.Create(&good)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
}
func GoodOrderList(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var data []model.GoodOrderList
	redis_key := "list_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("good_orders").
			Select(
				"good_orders.id AS OrderId",
				"goods.`name` AS `Name`",
				"goods.content AS Content",
				"good_orders.order_code AS OrderCode",
				"good_orders.order_price AS OrderPrice",
			).
			Joins("LEFT JOIN goods ON good_orders.gid = goods.id").
			Offset(offset).Limit(size).
			Find(&data)
		jsonData, _ := json.Marshal(data)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &data)
	}
	var total int64
	model.DB.Model(&model.GoodOrder{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  data,
		"total": total,
	})
}
func GoodOrderListId(c *gin.Context) {
	id, _ := strconv.Atoi(c.Query("id"))
	var data model.GoodOrderList
	redis_key := "list_id_"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("good_orders").
			Select(
				"good_orders.id AS OrderId",
				"goods.`name` AS `Name`",
				"goods.content AS Content",
				"good_orders.order_code AS OrderCode",
				"good_orders.order_price AS OrderPrice",
			).
			Joins("LEFT JOIN goods ON good_orders.gid = goods.id").
			Where("good_orders.id =?", id).
			Find(&data)
		jsonData, _ := json.Marshal(data)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &data)
	}
	var total int64
	model.DB.Model(&data).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  data,
		"total": total,
	})
}
